package com.ls.mysql.filter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 编码格式过滤 & 跨域处理
 */
public class ADomain implements HandlerInterceptor {

    //controller之前，分配请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); //
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTION,PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-Type,X-Custom-Header,Accept,Access-Token");
        // 设置可以暴露在外的响应头
        response.setHeader("Access-Control-Expose-Headers", "checkTokenResult");
        response.setHeader("Access-Control-Expose-Headers", "message");
        /*
         * 允许cookie跨域
         */
        // 指示的请求的响应是否可以暴露于该页面。当返回true时他可以被暴露Credentials
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //Credentials no-cache： 在发布缓存副本之前，强制要求缓存把请求提交给原始服务器进行验证。
        response.setHeader("Cache-Control", "no-cache");
//        if(request.getMethod().equals(RequestMethod.OPTIONS.name())) {
//            response.setStatus(HttpStatus.OK.value());
//            return false;
//        }
        return true;
    }

    //controller之后执行
    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //请求完成后都会执行：释放资源
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
